<!-- 角色信息 -->
<!-- 角色信息 -->
<template>
  <div>
    <el-dialog v-model="dialogVisible" width="370" :title="title" draggable appendToBody destroyOnClose lockScroll :closeOnClickModal="false">
      <el-form ref="elFormRef" :model="formData" :rules="rules" scrollToError statusIcon>
        <el-form-item label="图片" prop="bannerUrl" required labelWidth="6em">
          <rest-upload-qn
            v-model="formData.bannerUrl"
            folder="app/banner"
            :accept="['.png', '.jpg', '.svg', '.webp']"
            :limit="1"
            :width="252"
            :height="128"
            :afterSelectFile="openCropper"
          ></rest-upload-qn>
        </el-form-item>
        <el-form-item label="位置" prop="bannerType" required labelWidth="6em">
          <el-radio-group v-model="formData.bannerType">
            <el-radio label="首页" :value="1"></el-radio>
            <el-radio label="追剧" :value="2"></el-radio>
            <el-radio label="推荐" :value="3"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="类型" prop="jumpType" required labelWidth="6em">
          <el-radio-group v-model="formData.jumpType">
            <el-radio label="视频" :value="1"></el-radio>
            <el-radio label="链接" :value="2"></el-radio>
          </el-radio-group>
        </el-form-item>
        <div ref="parent">
          <el-form-item v-if="formData.jumpType === 1" label="请选择视频" prop="businessId" labelWidth="6em">
            <bubble-select-local
              v-model="drama"
              labelKey="dramaTitle"
              valueKey="dramaId"
              returnOriginal
              :axios="getPullDownListAxios"
              placeholder="请选择分类"
            ></bubble-select-local>
          </el-form-item>
          <el-form-item v-if="formData.jumpType === 2" key="el-form-item-2" label="链接地址" prop="bannerLink" labelWidth="6em">
            <el-input v-model="formData.bannerLink" :maxlength="200" placeholder="请输入链接地址" clearable></el-input>
          </el-form-item>
        </div>
        <el-form-item labelWidth="0em">
          <div style="width: 100%; padding-top: 20px">
            <el-button style="width: 100%" type="success" :loading="submitLoading" :disabled="submitLoading" :icon="IconPlus" @click="submit">保存</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>
    <rest-image-cropper ref="restImageCropperRef"></rest-image-cropper>
  </div>
</template>

<script setup lang="ts">
  import IconPlus from '~icons/ep/plus';
  import type { FormInstance, FormRules } from 'element-plus';
  import { type AppBanner, type AppBannerRequest, type Drama, addAppBannerAxios, editAppBannerAxios, getPullDownListAxios } from '@/api/app-management';
  import { useAutoAnimate } from '@formkit/auto-animate/vue';
  import RestImageCropper from '@/components/rest/rest-image-cropper/rest-image-cropper.vue';

  type $AddShowData = {
    type: 'add';
    /** 添加时的回调 */
    addCallBack: () => void;
  };
  type $EditShowData = {
    type: 'edit';
    /** 角色 */
    appBanner: AppBanner;
    /** 编辑时的回调 */
    editCallBack: () => void;
  };

  const [parent] = useAutoAnimate();
  const restImageCropperRef: $RefComp<'RestImageCropper'> = ref(null);

  let addCallBack: $AddShowData['addCallBack'] | undefined = undefined;
  let editCallBack: $EditShowData['editCallBack'] | undefined = undefined;
  const submitLoading = ref(false);
  const dialogVisible = ref(false);
  const drama = ref<Drama | undefined>(undefined);
  const elFormRef: Ref<FormInstance | null> = ref(null);
  const title: Ref<string> = ref('');
  const formData: AppBannerRequest = reactive<AppBannerRequest>({
    bannerId: undefined,
    bannerLink: undefined,
    bannerType: 1,
    bannerUrl: '',
    businessId: undefined,
    jumpType: 1,
  });

  watch(
    () => drama.value,
    (val) => {
      formData.businessId = val?.dramaId;
    }
  );
  watch(
    () => formData.jumpType,
    (val) => {
      if (val === 1) {
        formData.businessId = drama.value?.dramaId;
        formData.bannerLink = '';
      } else {
        formData.businessId = undefined;
        formData.bannerLink = '';
      }
    }
  );

  const rules = computed<FormRules>(() => {
    const _rules: FormRules = {
      bannerUrl: [{ required: true, type: 'string', message: '请上传图片', trigger: ['blur', 'change'] }],
      bannerType: [
        { required: true, type: 'number', message: `请选择位置`, trigger: ['blur', 'change'] },
        { required: true, type: 'enum', enum: [1, 2, 3], message: `位置不合法`, trigger: ['blur', 'change'] },
      ],
      jumpType: [
        { required: true, type: 'number', message: `请选择跳转类型`, trigger: ['blur', 'change'] },
        { required: true, type: 'enum', enum: [1, 2], message: `跳转类型不合法`, trigger: ['blur', 'change'] },
      ],
    };
    if (formData.jumpType === 1) {
      _rules.businessId = [{ required: true, type: 'number', message: '请选择短剧', trigger: ['blur', 'change'] }];
    } else if (formData.jumpType === 2) {
      _rules.bannerLink = [
        { required: true, type: 'string', message: '请输入跳转链接', trigger: ['blur', 'change'] },
        { required: true, type: 'url', message: '跳转链接不合法', trigger: ['blur', 'change'] },
      ];
    }

    return _rules;
  });

  /**
   * 显示
   */
  function show(data: $AddShowData | $EditShowData) {
    editCallBack = 'editCallBack' in data && typeof data.editCallBack === 'function' ? data.editCallBack : undefined;
    addCallBack = 'addCallBack' in data && typeof data.addCallBack === 'function' ? data.addCallBack : undefined;
    title.value = data.type === 'edit' ? '编辑轮播图' : '新增轮播图';

    dialogVisible.value = true;
    if (data.type === 'edit' && typeof data.appBanner) {
      formData.jumpType = data.appBanner.jumpType ?? 1;
      nextTick(() => {
        formData.bannerLink = data.appBanner.bannerLink ?? undefined;
        formData.bannerType = data.appBanner.bannerType ?? 1;
        formData.bannerUrl = data.appBanner.bannerUrl ?? '';
        formData.businessId = data.appBanner.businessId ?? undefined;
        formData.bannerId = data.appBanner.bannerId ?? 1;
        drama.value = { dramaId: data.appBanner.businessId, dramaTitle: data.appBanner.dramaTitle };
      });
    } else {
      formData.jumpType = 1;
      formData.bannerLink = undefined;
      formData.bannerType = 1;
      formData.bannerUrl = '';
      formData.businessId = undefined;
      formData.bannerId = undefined;
      drama.value = undefined;
    }
  }

  /**
   * 隐藏
   */
  function hide() {
    dialogVisible.value = false;
  }
  /** 打开裁剪框 */
  function openCropper(files: File[]): Promise<File[]> {
    return new Promise((resolve, reject) => {
      const file = files[0];
      if (file) {
        restImageCropperRef.value?.show({
          file,
          cropperOptions: { aspectRatio: 1260 / 640, autoCropArea: 1 },
          croppedCanvasOptions: { width: 1260, height: 640 },
          fail: () => {
            reject(null);
          },
          success: (res: File) => {
            resolve([res] as File[]);
          },
        });
      } else {
        resolve(files);
      }
    });
  }

  /** 提交 */
  async function submit() {
    try {
      await elFormRef.value?.validate();
      try {
        if (formData.bannerId) {
          await editAppBannerAxios(formData);
          typeof editCallBack === 'function' && editCallBack();
        } else {
          await addAppBannerAxios(formData);
          typeof addCallBack === 'function' && addCallBack();
        }
        ElToast.success('提交成功');
        hide();
      } catch (error) {
        ElToast.error(error.msg || '提交失败，-BD003');
      }
    } catch (error) {
      ElToast.error('提交失败，请完善表单，-BD002');
    }
  }

  defineExpose({ show, hide });
</script>
